﻿@page "/orders/create"

@using Microsoft.EntityFrameworkCore
@using BlazorAppAuth.Models
@inject IDbContextFactory<BlazorAppAuth.Data.BlazorAppAuthContext> DbFactory
@inject NavigationManager NavigationManager
@rendermode InteractiveServer
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target ="#createOrderModal" @onclick="RefreshOrder" >
	新增订单
</button>


<div class="modal fade" id="createOrderModal" data-bs-backdrop="static" tabindex="-1">
	<div class="modal-dialog modal-dialog-centered modal-xl  modal-dialog-scrollable">
		<div class="modal-content">
			<div class="modal-header">
				<h1 class="modal-title fs-5" id="exampleModalToggleLabel2">新增订单</h1>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				@if (WizardStep == 1) { 
				<EditForm method="post" EditContext="FormEditContext"  FormName="create" Enhance>
					<DataAnnotationsValidator />
					<ValidationSummary class="text-danger" />
					<div class="mb-3">
						<h4 for="orderid" class="form-label">订单编号: @Order.OrderId</h4>
					</div>
					<div class="mb-3">
						<label for="ordertype" class="form-label">订单类型:</label>
						<InputSelect id="ordertype" @bind-Value="Order.OrderType" @bind-Value:after="HandleOrderTypeChange" class="form-control">
							@foreach (var type in Constracts.ConvertToList(typeof(Constracts.OrderType)))
							{
								<option value="@type">@type</option>
							}
						</InputSelect>
						<ValidationMessage For="() => Order.OrderType" class="text-danger" />
					</div>
					<div class="mb-3">
						<label for="usertype" class="form-label">用户类型:</label>
						<InputText id="usertype" @bind-Value="Order.UserType" class="form-control" readonly />
						<ValidationMessage For="() => Order.UserType" class="text-danger" />
					</div>
					<div class="mb-3">
						<label for="username" class="form-label">用户名:</label>
						<InputText id="username" @bind-Value="Order.UserName" class="form-control" readonly />
						<ValidationMessage For="() => Order.UserName" class="text-danger" />
					</div>
					<div class="mb-3">
						<label for="starttime" class="form-label">启动时间:</label>
						<InputDate Type="InputDateType.DateTimeLocal" id="starttime" @bind-Value="Order.StartTime" class="form-control" />
						<ValidationMessage For="() => Order.StartTime" class="text-danger" />
					</div>

					<div class="mb-3">
						<label for="quantity" class="form-label">数量:</label>
						<InputNumber id="quantity" @bind-Value="Order.Quantity" class="form-control" />
						<ValidationMessage For="() => Order.Quantity" class="text-danger" />
					</div>
					<div class="mb-3">
						<label for="priority" class="form-label" >优先级:</label>
						<InputSelect id="priority" @bind-Value="Order.Priority" @bind-Value:after="OnPriorityChange" disabled="@(IsPriorityDisabled)" class="form-control">
							<option value="">无</option>
							<option value="钻孔优先">钻孔优先</option>
							<option value="装配优先">装配优先</option>
						</InputSelect>
						<ValidationMessage For="() => Order.Priority" class="text-danger" />
					</div>

					<div class="mb-3">
						<button type="button" data-bs-target="#addParamModal" data-bs-toggle="modal" class="btn btn-primary" disabled="@(IsButtonDisabled)">配置参数</button>
					</div>
				</EditForm>
				}
				@if (WizardStep == 2)
				{
					<OrderPreview Order="@Order" />
				}
				
			</div>
		
			<div class="modal-footer">
				@if (WizardStep == 1)
				{
					<button type="button" class="btn btn-primary" @onclick="(()=> WizardStep = 2)">下一步</button>
					
				}
				@if (WizardStep == 2)
				{
					<button type="button" class="btn btn-primary" @onclick="PrevStep">上一步</button>
					<button type="button" class="btn btn-primary" @onclick="DoSubmit">新增</button>
				}
				
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="addParamModal" data-bs-backdrop="static" tabindex="-1">
	<div class="modal-dialog modal-dialog-centered modal-xl  modal-dialog-scrollable">
		<div class="modal-content">
			<div class="modal-header">
				<h1 class="modal-title fs-5" id="exampleModalToggleLabel2">工艺参数</h1>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				<div class="mb-3">
					<label for="assemblytime" class="form-label">装配时间:</label>
					<InputNumber id="assemblytime" @bind-Value="Order.AssemblyTime" class="form-control" />
				</div>
				<div class="mb-3">
					<label for="drillingtime" class="form-label">钻孔时间:</label>
					<InputNumber id="drillingtime" @bind-Value="Order.DrillingTime" class="form-control" />
				</div>
				<div class="mb-3">
					<label for="assemblycount" class="form-label">装配次数:</label>
					<InputNumber id="assemblycount" @bind-Value="Order.AssemblyCount" class="form-control" />
				</div>
				<div class="mb-3">
					<label for="drillingcount" class="form-label">钻孔次数:</label>
					<InputNumber id="drillingcount" @bind-Value="Order.DrillingCount" class="form-control" />
				</div>
			</div>
			<div class="modal-footer">
				<button class="btn btn-primary" data-bs-target="#createOrderModal" data-bs-toggle="modal">返回</button>
			</div>
		</div>
	</div>
</div>

@code {

	[SupplyParameterFromForm]
	public Order Order { get; set; } = new();

	[CascadingParameter]
	private Task<AuthenticationState> authenticationStateTask { get; set; }

	[Parameter]
	public EventCallback OnOrderCreated { get; set; }

	private EditContext FormEditContext { get; set; }

	int WizardStep = 1;

	bool IsButtonDisabled = true;
	bool IsPriorityDisabled = false;

	string currentUserName = "";
	string currentUserRole = "";


	protected override async void OnInitialized()
	{

		var context = DbFactory.CreateDbContext();
		var authState = await authenticationStateTask;
		var user = authState.User;
		currentUserName = user.Identity.Name;
		currentUserRole = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value ?? "未知角色";

		await RefreshOrder();

		FormEditContext = new EditContext(Order);
	}


	protected void HandleOrderTypeChange()
	{
		bool isOrderTypeW101OrW102 = Order.OrderType.Equals("W101") || Order.OrderType.Equals("W102");
		IsPriorityDisabled = !isOrderTypeW101OrW102;
		if (IsPriorityDisabled)
		{
			Order.Priority = "";
		}
	}

	protected void OnPriorityChange()
	{
		IsButtonDisabled = Order.Priority.Equals("");

	}

	private void fillOrderData()
	{
		Order.OrderTime = DateTime.Now;
		Order.OrderStatus = Constracts.OrderStatusType.待下发.ToString();
	}

	private void PrevStep()
	{
		WizardStep = 1;

		StateHasChanged();
	}

	private async void DoSubmit()
	{
		if (FormEditContext.Validate())
		{

			await AddOrder();
			// close dialog
			await js.InvokeVoidAsync("closeDialog", "createOrderModal");
		}
	}

	protected async Task RefreshOrder()
	{
		WizardStep = 1;
		var context = DbFactory.CreateDbContext();
		var maxOderId = await context.Order.MaxAsync(o => o.Id);
		Order = new Order
		{
				UserName = currentUserName,
				OrderTime = DateTime.Now,
				StartTime = DateTime.Now,
				UserType = currentUserRole,
				OrderId = maxOderId + 1,
				OrderType = Constracts.OrderType.W101.ToString(),
				OrderStatus = Constracts.OrderStatusType.待下发.ToString(),
				Priority = ""

		};
	}


	public async Task AddOrder()
	{
		using var context = DbFactory.CreateDbContext();
		fillOrderData();
		context.Order.Add(Order);
		await context.SaveChangesAsync();
		// reset order
		await RefreshOrder();

		await OnOrderCreated.InvokeAsync();

	}
}
